package initial

import (
	"core/env"
	"core/graylog"
	"core/ipip"
	"core/minio_client"
	"core/mysql"
	"core/mysql_sync"
	"core/rds"
	"core/utils"
	"db"

	"github.com/json-iterator/go/extra"
)

func Init(runMode string) (closeFunc func(), err error) {
	utils.Info("runMode", runMode)
	// json 设置默认转换格式 user_name 的形式
	extra.SetNamingStrategy(extra.LowerCaseWithUnderscores)

	basicPath := getBasicPath(runMode)

	// 初始化配置
	err = env.InitEnv(runMode, basicPath)
	if err != nil {
		utils.Error(err)
		return
	}
	utils.Info("[init env ok]", env.RunMode)
	err = env.InitConf(basicPath)
	if err != nil {
		utils.Error(err)
		return
	}
	utils.Info("[init config ok]", env.RunMode)

	// 初始化graylog
	graylog.Init(&graylog.GrayConfig{
		Application: "jigsaw",
		GraylogHost: env.Conf.GraylogIp,
		RunMode:     string(runMode),
	})
	utils.Info("[init graylog ok]", env.Conf.GraylogIp)

	err = ipip.Init(basicPath)
	if err != nil {
		return
	}
	utils.Info("[init ip ok]")

	// 初始化文件服务器sdk
	err = minio_client.Init()
	if err != nil {
		utils.Error(err)
		return
	}
	utils.Info("[init minio ok]")

	// 初始化数据库引擎
	closeRds, err := rds.InitRedis()
	if err != nil {
		utils.Error(err)
		return
	}
	utils.Info("[init redis ok]", env.Conf.RedisAddr)
	err = mysql.InitXorm()
	if err != nil {
		utils.Error(err)
		return
	}
	utils.Info("[init mysql ok]", env.Conf.XOrmDriverName, env.Conf.XOrmDataSourceName)
	err = mysql_sync.SyncTables()
	if err != nil {
		utils.Error(err)
		return
	}
	utils.Info("[sync table ok]")

	if runMode == env.RunModeProd || runMode == env.RunModeDev || runMode == env.RunModeLocal {
		go db.RunSyncLoop()
	}
	if runMode == env.RunModeAdminDev || runMode == env.RunModeAdminLocal || runMode == env.RunModeAdminProd {
		go db.RunResizePicLoop()
	}

	closeFunc = func() {
		closeRds()
	}
	return
}

func getBasicPath(runMode string) (basicPath string) {
	switch runMode {
	case env.RunModeTest:
		basicPath = "../"
	case env.RunModeTestDB:
		basicPath = "../../../../"
	case env.RunModeTestCore:
		basicPath = "../../"
	case env.RunModeLocal:
		basicPath = "../../"
	case env.RunModeDev:
		basicPath = "./"
	case env.RunModeProd:
		basicPath = "./"
	case env.RunModeAdminLocal:
		basicPath = "../../"
	case env.RunModeAdminDev:
		basicPath = "./"
	case env.RunModeAdminProd:
		basicPath = "./"
	case env.RunModeAdminProdJigsaw:
		basicPath = "./"
	}
	return
}
